package com.heima.comment.service.impl;

import com.heima.comment.service.CommentHotService;
import com.heima.model.comment.pojos.ApComment;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;

/**
 * @author huan
 * @serial 每天一百行, 致敬未来的自己
 * @Description
 */
@Service
@Slf4j
public class CommentHotServiceImpl implements CommentHotService {
    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 处理热点评论
     *
     * @param apComment 评论信息
     */
    @Async("taskExecutor")
    public void hotCommentExecutor(ApComment apComment) {
        log.info("异步计算热点文章==================> 开始");
        // 1. 查询当前文章下的所有热点评论集合
        //     1.1 按照文章id   flag=1(热点文章)   点赞降序
        Query query = Query.query(Criteria.where("articleId").is(apComment.getArticleId()).and("flag").is(1)).with(Sort.by(Sort.Direction.DESC, "likes"));
        List<ApComment> apCommentList = mongoTemplate.find(query, ApComment.class);
        // 2. 如果 热评集合为空  或  热评数量小于5 直接将当前评论改为热评
        if (CollectionUtils.isEmpty(apCommentList) || apCommentList.size() < 5) {
            mongoTemplate.updateMulti(Query.query(Criteria.where("id").is(apComment.getId())), new Update().set("flag", 1), ApComment.class);
        }
        // 3. 如果热评数量大于等于 5
        // 3.1  获取热评集合中 最后点赞数量最少的热评
        apCommentList.sort(Comparator.comparingInt(ApComment::getLikes));
        if (apCommentList.size() >= 5) {
            ApComment minComment = apCommentList.get(0);
            // 3.2 和当前评论点赞数量做对比  谁的点赞数量多 改为热评
            boolean flag = minComment.getLikes() > apComment.getLikes();
            //当前评论为热评
            if (!flag) {
                mongoTemplate.updateMulti(Query.query(Criteria.where("id").is(apComment.getId())), new Update().set("flag", 1), ApComment.class);
                mongoTemplate.updateMulti(Query.query(Criteria.where("id").is(minComment.getId())), new Update().set("flag", 0), ApComment.class);
            }
        }
        log.info("异步计算热点文章==================> 结束");
    }
}
